<script setup>
import { computed, onMounted, ref } from 'vue'
import router from "@/router"
import { saveFlow } from '../api/flow.js'
import { createToken } from '../api/autoIdempotent.js'
import { useRoute } from 'vue-router'
import { getByIdRoomTypeDetail } from "../api/roomtype"
import { getBasicInfo } from "../api/hotel"
import { createOrder } from "../api/orders"
import { decrRoomCount } from "../api/roominventory"
import dayjs from "dayjs"

// 页面参数
const route = useRoute()
const hotelId = route.query.hotelId
const roomTypeIdNum = Number(route.query.roomTypeId)
const checkInDate = route.query.checkInDate
const checkOutDate = route.query.checkOutDate
//从localstorage拿出userid
const userId = Number(localStorage.getItem("userId"))

// 表单输入
// const userName = ref('')
// const userPhone = ref('')
//判断有没有传过来name和phone
const userName = ref(route.query.userName || "")
const userPhone = ref(route.query.userPhone || "")

// 房间信息
const roomPrice = ref(0)
const hotel = ref({})
const room = ref({})

// token 防重复提交
const formToken = ref('')

// 页面加载状态
const loading = ref(false)

// 计算入住天数和总金额
const nights = dayjs(checkOutDate).diff(dayjs(checkInDate), 'day')
const money = computed(() => roomPrice.value * nights)

// 页面初始化
onMounted(() => {
  createFormToken()
  getHotelAndRoomDetail()
})

// 生成幂等 token
async function createFormToken() {
  try {
    const res = await createToken()
    formToken.value = res.data.data
    console.log("formToken=", formToken.value)
  } catch (err) {
    console.error("生成token失败", err)
    alert('生成token失败，请刷新页面重试')
  }
}

// 获取酒店和房型详情
async function getHotelAndRoomDetail() {
  try {
    const resHotel = await getBasicInfo(hotelId)
    const resRoom = await getByIdRoomTypeDetail(roomTypeIdNum)

    if (resHotel.data?.code === 200) {
      const h = resHotel.data.data
      hotel.value = {
        name: h.hotelName,
        province: h.province,
        city: h.city,
        county: h.county,
        street: h.street,
        contactPhone: h.contactPhone,
        img: h.hotelImage
      }
    }

    if (resRoom.data?.code === 200) {
      const r = resRoom.data.data
      room.value = {
        title: `${r.roomtypeName} · ${r.roomtypeCapacity}人`,
        desc: `${r.roomtypeDes} | ${r.roomArea}`,
        meal: r.meal || '无餐食'
      }
      roomPrice.value = r.roomtypePrice
    }
  } catch (err) {
    console.error("获取酒店或房型信息失败", err)
    alert('获取酒店或房型信息失败，请刷新页面重试')
  }
}
// 下单并支付（改写）
async function submitOrderAndPay() {
  if (!userName.value || !userPhone.value) {
    alert('请填写住客姓名和联系电话！')
    return
  }

  if (!formToken.value) {
    alert('token为空，请刷新页面重试')
    return
  }

  loading.value = true

  try {
    // ----------------- 1. 创建订单 -----------------
    const orderInfo = {
      orders: {
        hotelId: Number(hotelId),
        userId: userId,
      },
      orderDetails: [
        {
          roomtypeId: roomTypeIdNum,
          roomQuantity: 1,
          checkIn: checkInDate,
          checkOut: checkOutDate,
          userName: userName.value,
          userPhone: userPhone.value,
          proPrice: roomPrice.value,
          orderPrice: money.value
        }
      ]
    }

    const createOrderRes = await createOrder(orderInfo, formToken.value)




    console.log("11111",createOrderRes)


    console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>",createOrderRes)


    const orderData = createOrderRes.data?.data

    console.log("下单返回数据:", createOrderRes.data)
    console.log("订单ID:", orderData?.orderId)
    console.log("订单编号:", orderData?.orderNumber)

    if (!orderData?.orderId || !orderData?.orderNumber) {
      throw new Error('订单ID或订单编号为空，请检查后端返回')
    }
  //---------------------2. 锁库存---------------------------------
  const  decrRoomCountRes = await decrRoomCount(hotelId,roomTypeIdNum,checkInDate,checkOutDate)
  console.log(decrRoomCountRes)

    // ----------------- 3. 调用支付接口 -----------------
    const myorder = {
      orderId: orderData.orderId,
      orderNumber: orderData.orderNumber,
      hotelId:hotelId,
      hotelName: hotel.value.name,
      orderPrice: money.value,
      //userId: 1
      userId: userId
    }

    console.log("支付请求对象:", myorder)

    const payRes = await saveFlow(myorder, formToken.value)

    console.log("支付接口返回:", payRes)

    // if (!payRes.data) {
    //   throw new Error('支付接口返回为空')
    // }

    // ----------------- 4. 插入 HTML 表单并提交 -----------------
    const div = document.createElement('div')
    div.innerHTML = payRes.data
    document.body.appendChild(div)

    const form = div.querySelector('form')
    if (form) {
      form.submit()
    } else {
      console.error('支付表单不存在，请检查接口返回内容', payRes)
      alert('支付失败，请查看控制台调试信息')
    }

  } catch (err) {
    console.error('saveFlow接口调用失败:', err.response || err)
    // console.error('下单或支付失败', err)
    alert(err.message)
  } finally {
    loading.value = false
  }
}


// 返回酒店详情
function toDetail() {
  router.push({ path: '/hotelDetail' })
}
</script>



<template>
  <div class="order-container">
            <div v-if="loading">正在跳转到支付页面...</div>
            <div v-else>
              <!-- 其他内容 -->
            </div>
    <!-- 状态和费用明细 -->
    <div class="top-section">
      <div class="card status-card">
        <h2 class="status-title">待支付</h2>
        <p class="status-tip">库存有限请尽快支付，若超时未支付，订单将自动取消</p >
        <div class="action-buttons">
          <!-- <button class="cancel-btn" @click="toDetail">返回酒店详情页</button> -->
          <button class="pay-btn" @click="submitOrderAndPay">
            下单并支付 ¥{{ money }}
          </button>
        </div>
      </div>

      <div class="card cost-detail">
        <h3>费用明细</h3>
        <div class="cost-item">
          <span>房间单价</span>
          <span class="cost-value">¥{{ roomPrice }}</span>
        </div>
        <div class="cost-item">
          <span>入住天数</span>
          <span class="cost-value">{{ nights }} 晚</span>
        </div>
        <div class="cost-total">
          <span>应付总额</span>
          <span class="total-amount">¥{{ money }}</span>
        </div>
      </div>
    </div>

    <!-- 酒店信息 -->
    <div class="card hotel-info">
      <img :src="hotel.img" alt="酒店图片" class="hotel-img">
      <div>
        <h2 class="hotel-name">{{ hotel.name }}</h2>
        <p class="hotel-address">
          位置：{{ hotel.province }}{{ hotel.city }}{{ hotel.county }}{{ hotel.street }} | 联系电话：{{ hotel.contactPhone }}
        </p >
        <div class="room-info">
          <h3 class="room-title">{{ room.title }}</h3>
          <p class="room-desc">{{ room.desc }}</p >
          <p class="meal-info">餐食：{{ room.meal }}</p >
        </div>
      </div>
    </div>

    <!-- 入住与住客信息 -->
    <div class="card stay-guest">
      <div class="stay-info">
        <h3>入住信息</h3>
        <p class="stay-detail">入住：{{ checkInDate }} 12:00后</p >
        <p class="stay-detail">离店：{{ checkOutDate }} 12:00前</p >
        <p class="stay-detail">时长：{{ nights }}晚</p >
      </div>
      <div class="guest-info">
        <h3>住客信息</h3>
        <p class="guest-detail">姓名：<input type="text" v-model="userName" placeholder="请输入姓名"></p >
        <p class="guest-detail">电话：<input type="text" v-model="userPhone" placeholder="请输入手机号"></p >
      </div>
    </div>
  </div>
</template>

<style scoped>
.order-container {
  background-color: #f5f7fa;
  padding: 16px;
}
.top-section {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
}
.card {
  background: #fff;
  border-radius: 4px;
  padding: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}
.status-card {
  flex: 2;
  display: flex;
  flex-direction: column;
}
.status-card .action-buttons {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
.cost-detail {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.cost-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #333;
  margin: 8px 0;
}

.cost-item .cost-value {
  font-weight: 500;
  color: #333;
}

.cost-total {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-top: 16px;
  border-top: 1px solid #eee;
  padding-top: 8px;
}

.total-amount {
  color: #ff5722;
  font-size: 18px;
}

.status-title {
  color: #ff5722;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 8px;
}
.status-tip, .order-info {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}
.detail-link {
  color: #2196f3;
  text-decoration: none;
  font-size: 14px;
}
.hotel-info {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12px;
}
.hotel-img {
  width: 300px;
  /* height: 70px; */
  border-radius: 4px;
  margin-right: 12px;
}
.hotel-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}
.hotel-address {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
  display: flex;
  align-items: center;
}
.room-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}
.room-desc, .meal-info {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}
.stay-guest {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}
.stay-info, .guest-info {
  flex: 1;
}
.stay-detail, .guest-detail {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
}
.cost-item {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
}
.cost-original {
  color: #999;
  text-decoration: line-through;
}
.cost-discount {
  color: #ff5722;
}
.cost-total {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-top: 8px;
  display: flex;
  justify-content: space-between;
}
.total-amount {
  color: #ff5722;
  font-size: 18px;
}
.cancel-btn {
  border: 1px solid #2196f3;
  color: #2196f3;
  background: #fff;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}
.pay-btn {
  background: #ff5722;
  color: #fff;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}
</style>